package Controler;

import Module.Blog;
import Module.BlogDao;
import Module.User;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-11-28
 * Time: 20:24
 * To BE A Better Person-2020-3-2
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        BlogDao dao=new BlogDao();
        ArrayList<Blog> list=new ArrayList<>();
        ObjectMapper mapper=new ObjectMapper();
        String blogid= req.getParameter("blogid");
        if(blogid == null){
            try {
                list=dao.searchAll();
                String jsonString = mapper.writeValueAsString(list);
                resp.getWriter().write(jsonString);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else{

            Blog blog=dao.search(Integer.parseInt(blogid));
            String jsonString = mapper.writeValueAsString(blog);
            resp.getWriter().write(jsonString);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 1. 获取到用户的登录状态.
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        // 2. 读取请求的内容
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        if (title == null || title.equals("") || content == null || content.equals("")) {
            resp.setStatus(400);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("请求中的标题或正文不完整");
            return;
        }
        // 3. 构造 Blog 对象, 并插入到数据库中.
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        // 博客的作者. 作者是谁? 当前谁登录, 作者就是谁!!
        blog.setUserid(user.getUserid());
        BlogDao blogDao=new BlogDao();
        blogDao.addBlog(blog);
        // 4. 插入成功之后, 跳转到博客列表页.
        resp.setStatus(302);
        resp.setHeader("Location","blog_list.html");
    }
}
